package com.liunian.channelhandler.handler;

import com.liunian.WrpcBootstrap;
import com.liunian.exceptions.ResponseException;
import com.liunian.protection.CircuitBreaker;
import com.liunian.transport.message.WrpcRespose;
import com.liunian.wrpcenum.ResponseCode;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.SocketAddress;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 这是一用来测试的类
 * 这是一个入站的handler
 */
@Slf4j
public class MySimpleChannelInboundHandler extends SimpleChannelInboundHandler<WrpcRespose> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, WrpcRespose wrpcRespose) throws Exception {

        // 从全局的挂起的请求中寻找与之匹配的待处理的待处理的 completableFuture
        CompletableFuture<Object> completableFuture = WrpcBootstrap.PENDING_REQUEST.get(wrpcRespose.getRequestId());


        SocketAddress socketAddress = channelHandlerContext.channel().remoteAddress();
        Map<SocketAddress, CircuitBreaker> everyIpCircuitBreaker = WrpcBootstrap.getInstance().getConfiguration().getEveryIpCircuitBreaker();
        CircuitBreaker circuitBreaker = everyIpCircuitBreaker.get(socketAddress);
        byte code = wrpcRespose.getCode();
        if (code == ResponseCode.FAIL.getCode()) {
            circuitBreaker.recordErrorRequest();
            completableFuture.complete(null);
            log.error("当前id为[{}]的请求返回错误的结果，响应码[{}]",wrpcRespose.getRequestId(),wrpcRespose.getCode());
            throw new ResponseException(code,ResponseCode.FAIL.getDesc());
        } else  if (code == ResponseCode.RATE_LIMIT.getCode()) {
            circuitBreaker.recordErrorRequest();
            completableFuture.complete(null);
            log.error("当前id为[{}]的请求返回错误的结果，被限流，响应码[{}]",wrpcRespose.getRequestId(),wrpcRespose.getCode());
            throw new ResponseException(code,ResponseCode.RATE_LIMIT.getDesc());
        } else  if (code == ResponseCode.RESOURCE_NOT_FOUND.getCode()) {
            circuitBreaker.recordErrorRequest();
            completableFuture.complete(null);
            log.error("当前id为[{}]的请求返回错误的结果，未找到目标资源，响应码[{}]",wrpcRespose.getRequestId(),wrpcRespose.getCode());
            throw new ResponseException(code,ResponseCode.RESOURCE_NOT_FOUND.getDesc());
        } else  if (code == ResponseCode.SUCCESS.getCode()) {
            // 服务提供方给予的结果
            Object returnValue = wrpcRespose.getBody();
            completableFuture.complete(returnValue);
            if (log.isDebugEnabled()) {
                log.debug("已寻找到请求[{}]的completableFuture，处理响应结果。", wrpcRespose.getRequestId());
            }
        } else  if (code == ResponseCode.SUCCESS_HEART_BEAT.getCode()) {
            completableFuture.complete(null);
            if (log.isDebugEnabled()) {
                log.debug("已寻找到请求[{}]的completableFuture，处理心跳检测，处理响应结果。", wrpcRespose.getRequestId());
            }
        }

    }
}
